package com.bjqg.bjqg01.bjqg.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bjqg.bjqg01.bjqg.R;
import com.bjqg.bjqg01.bjqg.bean.UserLoginBean;
import com.bjqg.bjqg01.bjqg.utils.Constant;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;

import java.net.URLEncoder;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by bjqg01 on 2017/12/11.
 */
public class RegistUserActivity extends BaseActivity implements View.OnClickListener {

    private EditText zcPhone;
    private EditText zcYzNum;
    private TextView getzcnum;
    private EditText zcpwd1;
    private EditText zcpwd2;
    private TextView btnzc;
//    private TextView haszc;
    private ImageView back;
    private TextView toptitle;
    private ImageView select;
    private String getusername;
    private EditText zcName;
    private EditText zcEmail;
    private String getPhone;
    private String getYz;
    private String getpwd1;
    private String getpwd2;
    private String getName;
    private String getEmail;
    private String[] split1;
    private FrameLayout loadview;
    private CheckBox isCheck;
    private boolean isrun=false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registuser);
        initView();
    }

    private void initView() {
        zcPhone = (EditText) findViewById(R.id.zc_phone_num);//手机号
        zcYzNum = (EditText) findViewById(R.id.zc_yz_num);//验证码
        getzcnum = (TextView) findViewById(R.id.get_yz_num_zc);//获取验证码
        zcpwd1 = (EditText) findViewById(R.id.zc_pwd1);//密码1
        zcpwd2 = (EditText) findViewById(R.id.zc_pwd2);//密码2
        zcName = (EditText) findViewById(R.id.zc_name);//姓名
        zcEmail = (EditText) findViewById(R.id.zc_email);//email
        isCheck = (CheckBox) findViewById(R.id.ischeck);//协议

//        zcPhone.setText("18301230681");
//        zcYzNum.setText("0000");
//        zcpwd1.setText("123456");
//        zcpwd2.setText("123456");
//        zcName.setText("鹏1");
//        zcEmail.setText("1739299499@qq.com");

        loadview = (FrameLayout) findViewById(R.id.loading_view);
        btnzc = (TextView) findViewById(R.id.btn_zc);
        back = (ImageView) findViewById(R.id.back);
        toptitle = (TextView) findViewById(R.id.tv_top_title);
        select = (ImageView) findViewById(R.id.select);

        getzcnum.setOnClickListener(this);
        btnzc.setOnClickListener(this);
        back.setOnClickListener(this);

        toptitle.setText("用户注册");
        select.setVisibility(View.INVISIBLE);

//        getusername = zcPhone.getText().toString();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back://返回上界面
                finish();
                break;
            case R.id.btn_zc://立即注册

                loadview.setVisibility(View.VISIBLE);
                getText();
                getTextNotNull();

                getPhone = zcPhone.getText().toString().trim();
                if (!checkCellphone(getPhone)){
                    Toast.makeText(getApplicationContext(),"手机号不合法",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (isrun){
                    loadview.setVisibility(View.GONE);
                    isrun = false;
                    return;
                }
                String url = getUrl();
                getokgo(url);

                break;

            case R.id.get_yz_num_zc:
                getPhone = zcPhone.getText().toString().trim();
                if (getPhone.length()==0){
                    Toast.makeText(getApplicationContext(),"请输入手机号",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!checkCellphone(getPhone)){
                    Toast.makeText(getApplicationContext(),"手机号不合法",Toast.LENGTH_SHORT).show();
                    return;
                }
                getokgo(getUrls());
                Toast.makeText(getApplicationContext(),"获取验证码:0000",Toast.LENGTH_SHORT).show();
                isrun=false;
                break;
        }
    }

//    private String yema = "1";
    private Handler myHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
//                    UserLoginBean refreshinfo = msg.getData().getParcelable("userLoginInfo");
//                    yema = refreshinfo.getPageNum().toString();
//                    showListView(refreshinfo);
//                    List<UserLoginBean.DsBean> ds = refreshinfo.getDs();
//                    if (getusername.equals(ds.get(0).getPhoneNum())&& getusername.equals(ds.get(0).getPwd())){
                        loadview.setVisibility(View.GONE);
//                        Toast.makeText(RegistUserActivity.this, "登陆成功", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent();
                        intent.setClass(RegistUserActivity.this, RegistSuccessActivity.class);
                        startActivity(intent);
                        finish();
//                    }else{
//                        Toast.makeText(RegistUserActivity.this, "用户名或密码不正确", Toast.LENGTH_LONG).show();
//                        loadview.setVisibility(View.GONE);
//                    }
                    break;
                case 1:
                    UserLoginBean refreshinfo = msg.getData().getParcelable("userLoginInfo");
//                    yema = refreshinfo.getPageNum().toString();
//                    showListView(refreshinfo);
                    List<UserLoginBean.DsBean> ds = refreshinfo.getDs();
                    if (getPhone.equals(ds.get(0).getPhoneNum())){
                        loadview.setVisibility(View.GONE);
                        Toast.makeText(RegistUserActivity.this, "该手机号已存在", Toast.LENGTH_LONG).show();
                        isrun=true;
//                        Intent intent = new Intent();
//                        intent.setClass(LoginActivity.this, NewHomeActivity2.class);
//                        startActivity(intent);
//                        finish();
                    }
                    break;
            }
        }
    };

    private void getokgo(String url) {

//        String sqlwere="";
//        String sqlwhere= "jyxm=";

//        Log.e("pagenum: ", pagenum.toString());
//        String jyxmcode = URLEncoder.encode(jyxmstr);
//        final String[] strreturn = {""};
//        Log.e("getokgo:encode ", encode);
        OkGo.<String>get(url)
//        OkGo.<String>get("http://www.tjzj21erp.com:8098/Service1.asmx/SelectjycsDj?yema="+yema+"&sqlwhere=")
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<String> response) {
//                        if (sampleInfoBean.getDs().size()==0){
//                            int i=0;
                        Log.e("----------error","失败：------------------------okgo");
//                        }
                        String str= "<string xmlns=\"http://tempuri.org/\">";
                        String strend="</string>";
                        String strerror = "{\"ds\":{}}";
                        String[] split = response.body().toString().split(str);
//                        Log.e("onSuccess: ", ""+split[1]);
                        split1 = split[1].split(strend);
//                        if (split1[0].contains("\\")){
//                            split1[0] = split1[0].replace("\\", "/");
//                        }
                        Log.e("----------error","失败：------------------------okgo"+ split1[0]);
//                        strreturn[0] = split1[0];
                        if (strerror.equals(split1[0])){
                            Toast.makeText(RegistUserActivity.this,"可以注册手机号",Toast.LENGTH_SHORT).show();
                            loadview.setVisibility(View.GONE);
//                            username.setText("");
//                            userpwd.setText("");
                        }else if("插入成功".equals(split1[0])){
//                            Gson gson = new Gson();
//                            UserLoginBean userLoginInfo = gson.fromJson(split1[0], UserLoginBean.class);
                            Message message = Message.obtain();
                            Bundle bundle = new Bundle();
//                            bundle.putParcelable("userLoginInfo", userLoginInfo);
                            message.what = 0;
                            message.setData(bundle);
                            myHandler.sendMessage(message);
                        }else {
                            Gson gson = new Gson();
                            UserLoginBean userLoginInfo = gson.fromJson(split1[0], UserLoginBean.class);

                            Message message = Message.obtain();
                            Bundle bundle = new Bundle();
                            bundle.putParcelable("userLoginInfo", userLoginInfo);
                            message.what = 1;
                            message.setData(bundle);
                            myHandler.sendMessage(message);
                        }
                    }

                    @Override
                    public void onError(com.lzy.okgo.model.Response<String> response) {
                        super.onError(response);
//                        Log.e("----------error","失败：------------------------okgo");
                        Toast.makeText(RegistUserActivity.this,"服务器正忙，请稍后再试!",Toast.LENGTH_SHORT).show();
                        loadview.setVisibility(View.GONE);
                    }
                });

    }

    private String getUrls() {
        StringBuffer sb = new StringBuffer();
        getPhone = zcPhone.getText().toString().trim();
        if (getPhone!=null&&getPhone!=""&&!getPhone.equals("")){
            String usernamecode = URLEncoder.encode(getPhone);
            sb.append("phonenum="+usernamecode);
        }
//        if (getuserpwd!=null&&getuserpwd!=""&&!getuserpwd.equals("")){
//            if (sb.toString().length()!=0)sb.append("&");
//            String jyxmcode = URLEncoder.encode(getuserpwd);
//            sb.append("jyxm="+jyxmcode);
//        }
        String url = Constant.BASEURL+Constant.SELECTAPPUSER+"?" + sb.toString();
        Log.e("----------error","失败：------------------------"+url);
        return url;
    }

    @android.support.annotation.NonNull
    private String getUrl() {
        StringBuffer sb = new StringBuffer();
//        getText();
//        getTextNotNull();

        String phonecode = URLEncoder.encode(getPhone);
        sb.append("phonenum="+phonecode);
        String pwdcode = URLEncoder.encode(getpwd1);
        sb.append("&pwd="+pwdcode);
        String yzcode = URLEncoder.encode(getYz);
        sb.append("&yannum="+yzcode);
        String namecode = URLEncoder.encode(getName);
        sb.append("&xingming="+namecode);
        String emailcode = URLEncoder.encode(getEmail);
        sb.append("&emailnum="+emailcode);

//        String phonecode = URLEncoder.encode(getPhone);
//        sb.append("PhoneNum="+phonecode);
//        String pwdcode = URLEncoder.encode(getpwd1);
//        sb.append("Pwd="+pwdcode);
//        String yzcode = URLEncoder.encode(getYz);
//        sb.append("YanNum="+yzcode);
//        String namecode = URLEncoder.encode(getName);
//        sb.append("XingMing="+namecode);
//        String emailcode = URLEncoder.encode(getEmail);
//        sb.append("EmailNum="+emailcode);

//        if (getPhone!=null&&getPhone!=""&&!getPhone.equals("")){
//            String phonecode = URLEncoder.encode(getPhone);
//            sb.append("PhoneNum="+phonecode);
//        }
//        if (getpwd1!=null&&getpwd1!=""&&!getpwd1.equals("")){
//            if (sb.toString().length()!=0)sb.append("&");
//            String pwd = URLEncoder.encode(getpwd1);
//            sb.append("Pwd="+pwd);
//        }
        String url = Constant.BASEURL+Constant.INSERTAPPUSER+"?" + sb.toString();
        Log.e("----------error","失败：------------------------"+url);
        return url;
    }

    public void getTextNotNull(){
        if (getPhone==null&&getPhone.equals("")){
            Toast.makeText(getApplicationContext(),"手机号不能为空",Toast.LENGTH_SHORT).show();
            isrun=true;
        }else if (getYz==null&&getYz.equals("")){
            Toast.makeText(getApplicationContext(),"验证码不能为空",Toast.LENGTH_SHORT).show();
            isrun=true;
        }else if (getpwd1==null&&getpwd1.equals("")){
            Toast.makeText(getApplicationContext(),"密码不能为空",Toast.LENGTH_SHORT).show();
            isrun=true;
        }else if (getpwd2==null&&getpwd2.equals("")){
            Toast.makeText(getApplicationContext(),"密码不能为空",Toast.LENGTH_SHORT).show();
            isrun=true;
        }else if (!getpwd1.equals(getpwd2)){
            Toast.makeText(getApplicationContext(),"两次输入密码不一致",Toast.LENGTH_SHORT).show();
            isrun=true;
        }else if (getName==null&&getName.equals("")){
            Toast.makeText(getApplicationContext(),"姓名不能为空",Toast.LENGTH_SHORT).show();
            isrun=true;
        }else if(getEmail==null&&getEmail.equals("")){
            Toast.makeText(getApplicationContext(),"Email不能为空",Toast.LENGTH_SHORT).show();
            isrun=true;
        }else if (!isCheck.isChecked()){
            Toast.makeText(getApplicationContext(),"用户注册需要同意《注册协议》",Toast.LENGTH_SHORT).show();
            isrun=true;
        }
    }

    public void getText(){
        getPhone = zcPhone.getText().toString().trim();
        getYz = zcYzNum.getText().toString().trim();
        getpwd1 = zcpwd1.getText().toString().trim();
        getpwd2 = zcpwd2.getText().toString().trim();
        getName = zcName.getText().toString().trim();
        getEmail = zcEmail.getText().toString().trim();
    }

    /**
     * 验证手机号码
     *
     * 移动号码段:139、138、137、136、135、134、150、151、152、157、158、159、182、183、187、188、147、182
     * 联通号码段:130、131、132、136、185、186、145
     * 电信号码段:133、153、180、189、177
     *
     * @param cellphone
     * @return
     */
    public static boolean checkCellphone(String cellphone) {
        String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,1,2,3,5-9])|(177))\\d{8}$";
        Pattern pattern=Pattern.compile(regex);
        Matcher matcher=pattern.matcher(cellphone);
        return matcher.matches();
    }
}
